<template>
  <view class="container">
    <view class="title">
      <uni-icons @click="idCard()" :color="'#fff'" type="idCard" size="26"></uni-icons>
      <view>
        实名认证
        <view>更加真实，更受欢迎</view>
      </view>
    </view>
    <view class="form">
      <view class="formTop">请您使用有效身份证信息认证</view>
      <view class="formBtm">
        <uni-forms :modelValue="formData" label-width="120" ref="form" :rules="rules">
          <uni-forms-item label="真实姓名" name="certName">
            <uni-easyinput type="text" v-model="formData.certName" placeholder="请输入您的真实姓名" />
          </uni-forms-item>
          <uni-forms-item label="证件号码" name="certNo">
            <uni-easyinput type="text" v-model="formData.certNo" placeholder="请输入您的真实证件号码" />
          </uni-forms-item>
        </uni-forms>
        <view class="btn" @click="certification('form')">下一步，人脸识别</view>
        <view class="agreement">
          <radio value="r1" :checked="isAgree" @click="isAgree = !isAgree" />
          勾选后点击前往认证，即同意 <text class="link"
            @click="goinfo('pages/login/details/details', 'facialAgreement')">《人脸认证服务协议》</text>
        </view>
      </view>
    </view>
    <view class="universal-card warn">
      <view class="">
        <!-- <image src="@/static/mine/certification/jg.png" mode=""></image> -->
      </view>
      <text>实名仅用于您是否为真人用户，不会对信息做任何采集与保留，请放心使用。</text>
    </view>
  </view>
</template>

<script>
// import {
// 	identityAuthentication,
// 	updateBlindMemberUser
// } from '@/api/user'


import {
  identityAuthentication,
  getSing
} from '@/api/user'

export default {
  data () {
    return {
      isAgree: false,
      formData: {
        certName: '宁永辉',
        certNo: '623021198312111014',
      },
      rules: {
        certNo: {
          rules: [{
            required: true,
            errorMessage: '身份证不能为空',
          },
          {
            validateFunction: function (rule, value, data, callback) {
              let iphoneReg = /^([1-9]\d{5})(\d{4})(\d{2})(\d{2})(\d{3})(\d|X)$/
              if (!iphoneReg.test(value)) {
                callback('身份证式不正确，请重新填写')
              }
              return true
            },
          },
          ],
        },
        certName: {
          rules: [{
            required: true,
            errorMessage: '姓名不能为空',
          },],
        },
      },
    }
  },
  methods: {
    goinfo (e, id) {
      if (id) {
        uni.navigateTo({
          url: `/${e}?id=${id}`,
        })
      } else {
        uni.navigateTo({
          url: `/${e}`,
        })
      }
    },
    certification (ref) {
      if (!this.isAgree) {
        uni.showToast({
          title: '请勾选《人脸认证服务协议》',
          icon: 'none',
          duration: 2000,
        })
        return
      }
      this.$refs[ref].validate().then(res => {
        // 调用认证 SDK，获取 MetaInfo
        identityAuthentication(this.formData).then(res => {


          // 仅活体检测
          console.log("【uni log】CLICK ================> 仅活体检测");
          this.getServiceSign(0, "", 0);

          // 跳转
          // uni.navigateTo({
          //   url: `/pages/my/EditingInformation/EditingInformation`,
          // })
        })
      }).catch(err => {
        console.log('表单错误信息：', err);
      })
    },
    Back () {
      //uni.navigateBack()//默认delta:1
      uni.navigateBack({
        delta: 1, //返回层数，2则上上页
      })
    },
    // 调用认证 SDK，获取 MetaInfo
    getMetaInfo () {
      // 调用getMetaInfo获取MetaInfo数据
      var metaInfo = aliyunVerify.getMetaInfo()

      let p = uni.getSystemInfoSync().platform
      if (p === 'ios') {
        metaInfo = JSON.stringify(metaInfo)
      }

      return metaInfo
    },
    /**
     * 获取服务签名
     */
    getServiceSign (compareType, faceId, advance) {
      console.warn(">> dc >>>>>>>>>>>>>【uni log】METHOD ================> getSign:compareType=" + compareType + ".");

      getSing({
        name: this.formData.certName,
        idCard: this.formData.certNo,
      }).then((res) => {

        console.log("【uni log】getSignSuccess res=", res.data.data);
        let { sign, faceId, userId, nonce, orderNo } = res.data.data;
        console.warn("【uni log】getSignSuccess sign=" + sign);
        console.warn("【uni log】getSignSuccess faceId=" + faceId);
        console.warn("【uni log】getSignSuccess userId=" + userId);
        console.warn("【uni log】getSignSuccess nonce=" + nonce);
        console.warn("【uni log】getSignSuccess orderNo=" + orderNo);

        // 调用认证 SDK，获取 MetaInfo
        this.startWbFaceVerifyService(sign, faceId, compareType, advance);
      })

      // uni.request({
      //   method: 'POST',
      //   url: 'http://192.168.0.141:48082/app-api/tencent/getSing',
      //   data: {
      //     name: this.usernameInput,
      //     idCard: this.useridInput,
      //   },
      //   success: (res) => {
      //     console.log("【uni log】getSignSuccess res=", res.data.data);
      //     let { sign, faceId, userId, nonce, orderNo } = res.data.data;
      //     console.warn("【uni log】getSignSuccess sign=" + sign);
      //     console.warn("【uni log】getSignSuccess faceId=" + faceId);
      //     console.warn("【uni log】getSignSuccess userId=" + userId);
      //     console.warn("【uni log】getSignSuccess nonce=" + nonce);
      //     console.warn("【uni log】getSignSuccess orderNo=" + orderNo);

      //     // 调用认证 SDK，获取 MetaInfo
      //     this.startWbFaceVerifyService(sign, faceId, compareType, advance);
      //   },

      // });
    },
    /**
     * 拉起 face SDK
     */
    startWbFaceVerifyService (sign, faceId, compareType, advance) {
      console.log("【uni log】================> 拉起 face SDK！");
      // 调起 SDK
      if (advance == 0) {
        face.startWbFaceVerifyService({
          apiVersion: "1.0.0",
          appId: this.appid,
          nonce: this.nonce,
          userId: this.userId,
          sign: sign,
          orderNo: this.orderNo,
          licence: this.licence,
          faceId: faceId,
          compareType: compareType.toString(),
          sdkConfig: {
            //和iOS共有的配置参数
            showSuccessPage: false, //是否展示成功页面,默认不展示
            showFailurePage: false, //是否展示失败页面,默认不展示
            recordVideo: false, //是否录制视频,默认不录制
            checkVideo: false,//是否检查视频大小
            playVoice: false, //是否播放语音提示，默认不播放
            theme: '1', //sdk皮肤设置，0黑色，1白色
            customerTipsLoc: '0',//自定义提示的位置，0在预览框下面，1在预览框上面
            customerTipsInLive: '',//检测时的自定义提示语
            customerTipsInUpload: '',//上传时的自定义提示语
            customerLongTip: '',//自定义长提示语
            //android独有的配置参数
            isEnableLog: true, //是否打开刷脸native日志，请release版本关闭！！！
            //iOS独有的配置参数
            windowLevel: '1', //sdk中拉起人脸活体识别界面中使用UIWindow时的windowLevel配置
            manualCookie: true,//是否由SDK内部处理sdk网络请求的cookie
            useWindowSecene: false,
          }
        }, result => {
          console.log("【uni log】face SDK callback ================> result.", result);

          //scene区分回调场景
          let scene = result.scene;
          //登录失败，可以通过error获得失败原因
          if (scene == 'wb_face_callback_login_failure') {
            let res = result.res;
            let error = res.error;
            let tip = "登录失败:domain=" + error.domain + ",code=" + error.code + ",desc=" + error.desc + ",reason=" + error.reason;
            console.log(tip);
            uni.showToast({
              icon: 'none',
              title: tip
            });
            return;
          }

          //返回刷脸结果
          if (scene == "wb_face_callback_verify_result") {
            let res = result.res;
            //success区分是否刷脸成功
            let success = res.success;
            if (success) {
              //刷脸成功
              //还可以通过res拿到orderNo，sign，userImageString(用户刷脸base64 string照片)
              console.log("刷脸成功:liverate=" + res.liveRate + ",similarity=" + res.similarity);
              uni.showToast({
                icon: 'none',
                title: "刷脸成功:liverate=" + res.liveRate + ",similarity=" + res.similarity
              });
            } else {
              //刷脸失败
              let error = res.error;
              console.log("error=" + JSON.stringify(error));

              //可以通过domain区分是本地刷脸错误，还是人脸对比失败，
              let domain = error.domain;
              //如果是人脸对比失败，可以从res里拿到liveRate和similarity
              if (domain == "WBFaceErrorDomainCompareServer") {
                console.log("对比失败，liveRate=" + res.liveRate + "; similarity=" + res.similarity + ";sign=" + res.sign);
                uni.showToast({
                  icon: 'none',
                  title: "对比失败，liveRate=" + res.liveRate + "; similarity=" + res.similarity + ";sign=" + res.sign
                });
                return;
              }

              uni.showToast({
                icon: 'none',
                title: JSON.stringify(error)
              });
            }
          }
        });
      } else {
        let useAdvanceCompare;
        if (compareType == 2) {
          useAdvanceCompare = false;
        } else {
          useAdvanceCompare = true;
        }
        face.startAdvanceWbFaceVerifyService({
          apiVersion: "1.0.0",
          appId: this.appid,
          nonce: this.nonce,
          userId: this.userId,
          sign: sign,
          orderNo: this.orderNo,
          licence: this.licence,
          faceId: faceId,
          compareType: compareType.toString(),
          sdkConfig: {
            //和iOS共有的配置参数
            showSuccessPage: false, //是否展示成功页面,默认不展示
            showFailurePage: false, //是否展示失败页面,默认不展示
            recordVideo: false, //是否录制视频,默认不录制
            checkVideo: false,//是否检查视频大小
            playVoice: false, //是否播放语音提示，默认不播放
            theme: '1', //sdk皮肤设置，0黑色，1白色
            customerTipsLoc: '0',//自定义提示的位置，0在预览框下面，1在预览框上面
            customerTipsInLive: '',//检测时的自定义提示语
            customerTipsInUpload: '',//上传时的自定义提示语
            customerLongTip: '',//自定义长提示语
            //android独有的配置参数
            isEnableLog: true, //是否打开刷脸native日志，请release版本关闭！！！
            //iOS独有的配置参数
            windowLevel: '1', //sdk中拉起人脸活体识别界面中使用UIWindow时的windowLevel配置
            manualCookie: true,//是否由SDK内部处理sdk网络请求的cookie
            useWindowScene: false,
            useAdvanceCompare: useAdvanceCompare
          }
        }, result => {
          console.log("【uni log】face SDK callback ================> result.");

          //scene区分回调场景
          let scene = result.scene;
          //登录失败，可以通过error获得失败原因
          if (scene == 'wb_face_callback_login_failure') {
            let res = result.res;
            let error = res.error;
            let tip = "登录失败:domain=" + error.domain + ",code=" + error.code + ",desc=" + error.desc + ",reason=" + error.reason;
            console.log(tip);
            uni.showToast({
              icon: 'none',
              title: tip
            });
            return;
          }

          //返回刷脸结果
          if (scene == "wb_face_callback_verify_result") {
            let res = result.res;
            //success区分是否刷脸成功
            let success = res.success;
            if (success) {
              //刷脸成功
              //还可以通过res拿到orderNo，sign，userImageString(用户刷脸base64 string照片)
              console.log("刷脸成功:liverate=" + res.liveRate + ",similarity=" + res.similarity);
              let riskInfo = res.riskInfo;
              uni.showToast({
                icon: 'none',
                title: "刷脸成功:liverate=" + res.liveRate + ",similarity=" + res.similarity + ",deviceInfoLevel=" + riskInfo.deviceInfoLevel + ",deviceInfoTag=" + riskInfo.deviceInfoTag + ",riskInfoLevel=" + riskInfo.riskInfoLevel + ",riskInfoTag=" + riskInfo.riskInfoTag
              });
            } else {
              //刷脸失败
              let error = res.error;
              console.log("error=" + JSON.stringify(error));

              //可以通过domain区分是本地刷脸错误，还是人脸对比失败，
              let domain = error.domain;
              //如果是人脸对比失败，可以从res里拿到liveRate和similarity
              if (domain == "WBFaceErrorDomainCompareServer") {
                console.log("对比失败，liveRate=" + res.liveRate + "; similarity=" + res.similarity + ";sign=" + res.sign);
                uni.showToast({
                  icon: 'none',
                  title: "对比失败，liveRate=" + res.liveRate + "; similarity=" + res.similarity + ";sign=" + res.sign
                });
                return;
              }

              uni.showToast({
                icon: 'none',
                title: JSON.stringify(error)
              });
            }
          }
        });
      }
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  background-image: url('@/static/login/bg.png');
  background-size: 100% 576rpx;
  background-repeat: no-repeat;
  min-height: 100vh;
  padding: 60rpx 30rpx 0;
  box-sizing: border-box;

  .title {
    font-size: 50rpx;
    font-weight: bold;
    color: #ffffff;

    &>view {
      view {
        margin-top: 17rpx;
        font-size: 28rpx;
        font-weight: 500;
      }
    }
  }

  .warn {
    display: flex;
    font-size: 24rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #999999;

    image {
      width: 23rpx;
      height: 23rpx;
      margin-right: 11rpx;
      position: relative;
      top: 5rpx;
    }
  }

  .form {
    width: 690rpx;
    min-height: 553rpx;
    background: #ffffff;
    border-radius: 15rpx;
    margin-top: 69rpx;
    margin-bottom: 25rpx;

    .formTop {
      width: 690rpx;
      min-height: 107rpx;
      background: #f3f5f9;
      border-radius: 15rpx 15rpx 0 0;
      line-height: 107rpx;
      padding-left: 19rpx;
      box-sizing: border-box;
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
    }

    .formBtm {
      padding: 42rpx 20rpx 30rpx;
      box-sizing: border-box;

      .agreement {
        margin-top: 27rpx;
        font-size: 24rpx;
        font-weight: 500;
        color: #999999;
        text-align: center;

        line-height: 30rpx;

        /deep/.uni-radio-input {
          width: 22rpx;
          height: 22rpx;
        }
      }

      .btn {
        background-color: #3B6CFE;
        border-radius: 60rpx;
        width: 650rpx;
        height: 79rpx;
        font-size: 28rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #ffffff;
        line-height: 79rpx;
        text-align: center;
        margin-top: 65rpx;
      }

      /deep/.uni-forms-item__label {
        font-size: 30rpx;
        font-weight: 500;
        color: #333333;
      }

      /deep/.uni-easyinput__placeholder-class {
        font-size: 30rpx !important;
      }

      /deep/.uni-forms-item {
        height: 85rpx;
        padding: 0 20rpx 0 40rpx;
        box-sizing: border-box;
        background: #f3f5f9;
        border-radius: 39rpx;
        align-items: center;

        .uni-easyinput__placeholder-class {
          font-size: 26rpx;
        }
      }

      /deep/.uni-input-input {
        font-size: 30rpx;
      }

      /deep/.uni-easyinput__content {
        background-color: #fff0 !important;
      }

      /deep/.is-input-border {
        border: none;
      }
    }
  }

  .link {
    color: #7b66fe;
  }
}
</style>